//
//  ZCTakeCarDetailViewController.m
//  ZhiChe-Wms
//
//  Created by 高睿婕 on 2018/8/16.
//  Copyright © 2018年 Regina. All rights reserved.
//

#import "ZCTakeCarDetailViewController.h"
#import "ZCTaskTotalNumTableViewCell.h"
#import "ZCTaskHandleTableViewCell.h"
#import "ZCTaskModel.h"
#import "UWRQViewController.h"
#import "ZCAbnormalSignViewController.h"

static NSString *taskInfoCell = @"ZCTaskTotalNumTableViewCell";
static NSString *taskHandleCell = @"ZCTaskHandleTableViewCell";

@interface ZCTakeCarDetailViewController ()<UITableViewDelegate, UITableViewDataSource, ZCTaskHandleTableViewCellDelegate, uwRQDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) ZCTaskDetailModel *taskDetailModel;
@property (nonatomic, strong) MBProgressHUD *hud;
@end

@implementation ZCTakeCarDetailViewController

#pragma mark - 懒加载
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGHT) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            _tableView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0);
            _tableView.scrollIndicatorInsets = _tableView.contentInset;
            _tableView.estimatedRowHeight = 0;
            _tableView.estimatedSectionFooterHeight = 0;
            _tableView.estimatedSectionHeaderHeight = 0;
        }
        
        [_tableView registerClass:[ZCTaskTotalNumTableViewCell class] forCellReuseIdentifier:taskInfoCell];
        [_tableView registerClass:[ZCTaskHandleTableViewCell class] forCellReuseIdentifier:taskHandleCell];
    }
    return _tableView;
}


#pragma mark - 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    self.tabBarController.tabBar.hidden = YES;
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"任务详情";
    UIButton *leftButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    [leftButton setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(backToList) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    
    [self.view addSubview:self.tableView];
    self.hud = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:self.hud];
    [self.hud showAnimated:YES];
    [self loadData];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.hud hideAnimated:YES];
    self.hud.mode = MBProgressHUDModeIndeterminate;
}

#pragma mark - 按钮点击
- (void)backToList {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 网络请求
- (void)loadData {

    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:self.taskId forKey:@"id"];
//    [self.hud showAnimated:YES];
    __weak typeof(self)weakSelf = self;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [ZCHttpTool postWithURL:TaskDetail params:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if ([responseObject[@"success"] boolValue]) {
                [weakSelf.hud hideAnimated:YES];
                weakSelf.taskDetailModel = [ZCTaskDetailModel yy_modelWithDictionary:responseObject[@"data"]];
                
                [weakSelf.tableView reloadData];
                
                if ([self.taskDetailModel.taskType integerValue] == 10) {
                    if (Iphone5s) {
                        weakSelf.tableView.scrollEnabled = YES;
                    }else {
                        weakSelf.tableView.scrollEnabled = NO;
                    }
                }else if ([self.taskDetailModel.taskType integerValue] == 20) {
                    if ([self.taskDetailModel.taskStatus integerValue] != 10 && [self.taskDetailModel.taskStatus integerValue] != 20) {
                        if (Iphone5s) {
                            weakSelf.tableView.scrollEnabled = YES;
                        }else {
                            weakSelf.tableView.scrollEnabled = NO;
                        }
                    }else {
                        weakSelf.tableView.scrollEnabled = YES;
                    }
                }else if ([self.taskDetailModel.taskType integerValue] == 30) {
                    if ([self.taskDetailModel.taskStatus integerValue] != 10) {
                        if (Iphone5s) {
                            weakSelf.tableView.scrollEnabled = YES;
                        }else {
                            weakSelf.tableView.scrollEnabled = NO;
                        }
                    }else {
                        weakSelf.tableView.scrollEnabled = YES;
                    }
                }
            }else {
                weakSelf.hud.mode = MBProgressHUDModeText;
                weakSelf.hud.label.text = responseObject[@"message"];
                [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
            }
            
            
        } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
            weakSelf.hud.mode = MBProgressHUDModeText;
            weakSelf.hud.label.text = error.localizedDescription;
            [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
        }];
    });
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 7;
    }else {
        if (self.fromSearch) {
            return 5;
        }
        return 4;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        ZCTaskTotalNumTableViewCell *infoCell = [tableView dequeueReusableCellWithIdentifier:taskInfoCell forIndexPath:indexPath];
        infoCell.selectionStyle = UITableViewCellSelectionStyleNone;
        infoCell.line = YES;
        infoCell.titleColor = ZCColor(0x000000, 0.54);
        infoCell.contentColor = ZCColor(0x000000, 0.87);
        infoCell.titleFont = [UIFont systemFontOfSize:FontSize(30)];
        infoCell.contentFont = [UIFont systemFontOfSize:FontSize(30)];
        if (indexPath.row == 0) {
            infoCell.title = @"任务单";
            infoCell.content = self.taskDetailModel.taskId;
        }else if (indexPath.row == 1) {
            infoCell.title = @"订单号";
            infoCell.content = self.taskDetailModel.orderNo;
        }else if (indexPath.row == 2) {
            infoCell.title = @"车架号";
            infoCell.content = self.taskDetailModel.vin;
        }else if (indexPath.row == 3) {
            infoCell.title = @"任务类型";
            if ([self.taskDetailModel.taskType integerValue] == 10) {
                infoCell.content = @"寻车任务";
            }else if ([self.taskDetailModel.taskType integerValue] == 20) {
                infoCell.content = @"移车任务";
            }else if ([self.taskDetailModel.taskType integerValue] == 30) {
                infoCell.content = @"提车任务";
            }
        }else if (indexPath.row == 4) {
            infoCell.title = @"提车点";
            infoCell.content = self.taskDetailModel.originName;
        }else if (indexPath.row == 5) {
            infoCell.title = @"目的地";
            infoCell.content = self.taskDetailModel.destName;
        }else if (indexPath.row == 6) {
            infoCell.title = @"生成时间";
            infoCell.content = self.taskDetailModel.taskCreate;
        }
        
        return infoCell;
    }else {
        if (indexPath.row == 4) {
            ZCTaskHandleTableViewCell *handleCell = [tableView dequeueReusableCellWithIdentifier:taskHandleCell forIndexPath:indexPath];
            handleCell.selectionStyle = UITableViewCellSelectionStyleNone;
            handleCell.taskDetailModel = self.taskDetailModel;
            handleCell.delegate = self;
            return handleCell;
        }else {
            ZCTaskTotalNumTableViewCell *infoCell = [tableView dequeueReusableCellWithIdentifier:taskInfoCell forIndexPath:indexPath];
            infoCell.selectionStyle = UITableViewCellSelectionStyleNone;
            infoCell.line = YES;
            infoCell.titleColor = ZCColor(0x000000, 0.54);
            infoCell.contentColor = ZCColor(0x000000, 0.87);
            infoCell.titleFont = [UIFont systemFontOfSize:FontSize(30)];
            infoCell.contentFont = [UIFont systemFontOfSize:FontSize(30)];
            
            
            if (indexPath.row == 0) {
                infoCell.title = @"领取时间";
                infoCell.content = self.taskDetailModel.taskStart;
                return infoCell;
            }else if (indexPath.row == 1) {
                infoCell.title = @"完成时间";
                infoCell.content = self.taskDetailModel.taskFinish;
                return infoCell;
            }else if (indexPath.row == 2) {
                infoCell.title = @"状态";
                infoCell.contentColor = ZCColor(0xff8213, 1);
                if ([self.taskDetailModel.taskStatus integerValue] == 10) {
                    infoCell.content = @"创建";
                }else if ([self.taskDetailModel.taskStatus integerValue] == 20) {
                    infoCell.content = @"开始";
                }else if ([self.taskDetailModel.taskStatus integerValue] == 30) {
                    infoCell.content = @"完成";
                }else if ([self.taskDetailModel.taskStatus integerValue] == 50) {
                    infoCell.content = @"取消";
                }
                return infoCell;
            }else {
                infoCell.title = @"二维码";
                infoCell.contentColor = ZCColor(0xff8213, 1);
                infoCell.content = self.taskDetailModel.qrCode;
                return infoCell;
            }
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 1) {
        if (indexPath.row == 4) {
            if ([self.taskDetailModel.taskType integerValue] == 10) {
                if ([self.taskDetailModel.taskStatus integerValue] != 10 && [self.taskDetailModel.taskStatus integerValue] != 20) {
                    return CGFLOAT_MIN;
                }else {
                    return space(168);
                }
            }else if ([self.taskDetailModel.taskType integerValue] == 20) {
                if ([self.taskDetailModel.taskStatus integerValue] != 10 && [self.taskDetailModel.taskStatus integerValue] != 20) {
                    return space(168);
                }else {
                    return space(396);
                }
            }else if ([self.taskDetailModel.taskType integerValue] == 30) {
                if ([self.taskDetailModel.taskStatus integerValue] != 10) {
                    return space(168);
                }else {
                    return space(396);
                }
            }
            
        }
    }
    return space(90);
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
   
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    
    return [[UIView alloc] init];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc] init];
}

#pragma mark - ZCTaskHandleTableViewCellDelegate
- (void)taskHandleTableViewCellTaskButtonActionWithTaskDetailModel:(ZCTaskDetailModel *)detailModel {
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:detailModel.taskType forKey:@"taskType"];
    [params setObject:detailModel.taskId forKey:@"taskId"];
    if (self.taskDetailModel.pointId.length > 0) {
        [params setObject:self.taskDetailModel.pointId forKey:@"pointId"];
    }
    self.hud.mode = MBProgressHUDModeIndeterminate;
    self.hud.label.text = nil;
    [self.hud showAnimated:YES];
    __weak typeof(self)weakSelf = self;
    
    if ([detailModel.taskType integerValue] == 20) {
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            [ZCHttpTool postWithURL:FinishMove params:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                if ([responseObject[@"success"] boolValue]) {
//                    [weakSelf.hud hideAnimated:YES];
                    [weakSelf loadData];
                }else {
                    weakSelf.hud.mode = MBProgressHUDModeText;
                    weakSelf.hud.label.text = responseObject[@"message"];
                    [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
                }
                
            } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
                weakSelf.hud.mode = MBProgressHUDModeText;
                weakSelf.hud.label.text = error.localizedDescription;
                [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
            }];
        });
    }else {
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            [ZCHttpTool postWithURL:StartPick params:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                if ([responseObject[@"success"] boolValue]) {
//                    [weakSelf.hud hideAnimated:YES];
                    [weakSelf loadData];
                }else {
                    weakSelf.hud.mode = MBProgressHUDModeText;
                    weakSelf.hud.label.text = responseObject[@"message"];
                    [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
                }
                
            } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
                weakSelf.hud.mode = MBProgressHUDModeText;
                weakSelf.hud.label.text = error.localizedDescription;
                [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
            }];
        });
    }

}

- (void)taskHandleTableViewCellQRButtonActionWithTaskDetailModel:(ZCTaskDetailModel *)detailModel {
    UWRQViewController *qrCodeVC = [[UWRQViewController alloc] init];
    qrCodeVC.alertTitle = @"请扫描要赋的二维码";
    qrCodeVC.delegate = self;
    qrCodeVC.fromAuthierVC = NO;
    [self.navigationController pushViewController:qrCodeVC animated:YES];
}

- (void)taskHandleTableViewCellAbnormalActionWithTaskDetailModel:(ZCTaskDetailModel *)detailModel {
    ZCAbnormalSignViewController *signVC = [[ZCAbnormalSignViewController alloc] init];
    signVC.releaseId = detailModel.taskId;
    signVC.taskType = detailModel.taskType;
    [self.navigationController pushViewController:signVC animated:YES];
}

#pragma mark - uwRQDelegate
- (void)uwRQFinshedScan:(NSString *)result {
    NSArray *arr = [result componentsSeparatedByString:@","];
    NSString *keyId = [arr firstObject];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setObject:keyId forKey:@"qrCode"];
    [param setObject:self.taskId forKey:@"taskId"];
    [param setObject:self.taskType forKey:@"taskType"];
    if (self.taskDetailModel.pointId.length > 0) {
        [param setObject:self.taskDetailModel.pointId forKey:@"pointId"];
    }
    
    __weak typeof(self)weakSelf = self;
    self.hud.mode = MBProgressHUDModeIndeterminate;
    self.hud.label.text = nil;
    [self.hud showAnimated:YES];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [ZCHttpTool postWithURL:BindQRCode params:param success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if ([responseObject[@"success"] boolValue]) {
                [weakSelf loadData];
            }else {
                weakSelf.hud.mode = MBProgressHUDModeText;
                weakSelf.hud.label.text = responseObject[@"message"];
                [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
            }
            
        } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
            weakSelf.hud.mode = MBProgressHUDModeText;
            weakSelf.hud.label.text = @"赋码失败";
            [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
        }];
    });
}

@end
